// pages/productinfo/productinfo.js
const app = getApp()
const util = require("../../utils/util.js")
var WxParse = require('../../wxParse/wxParse.js');
Page({
  onShareAppMessage: function (res) {
    return {
      title: this.data.productinfo.Name,
      path: '/pages/productinfo/productinfo?id=' + this.data.productinfo.ID +'&userid=1',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    admin:{},
    productinfo:{APrice:0},
    opacity:0,
    bottom:-940,
    zindex:-1,
    hidestore:"hidestore1",
    formats: [],
    priceid:0,
    pricetext:"",
    price:"0",
    oprice:0,
    aprice:0,
    unit:"",
    count:1,
    librarycount:0,
    act:"",
    flag:"store", //收藏的标记
    select:"info",
    loadmore: 'block',
    nodata: 'none',
    nomore: 'none',
    page: 1,
    list:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '数据加载中...',
    })
    this.setData({ admin: app.AdminInfo});
    app.IsFlash = false;
    this.Find_ProductInfo(options.id);
  },
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '数据加载中...',
    })
    this.Find_ProductInfo(this.data.productinfo.ID);
    this.setData({ formats:[],priceid:0});
  },
  onReachBottom: function () {
    if (this.data.page > 1) {  //必须加上，否则上拉和下拉会同时触发
      this.Find_Reply();
    }
  },
  Find_Reply: function () {
    var that = this;
    var data = {};
    data.act = "Find_Reply";
    data.productid = this.data.productinfo.ID;
    data.page = that.data.page;
    app.Ajax(data, function (json) {
      var pagecount = Math.floor(Math.abs(json.count - 1) / json.pagesize) + 1;
      if (data.page > pagecount) { return; }
      that.setData({ list: that.data.list.concat(json.data), page: data.page + 1 });
      if (that.data.list.length == 0) {
        that.setData({ loadmore: 'none', nodata: 'block', nomore: 'none' });
      }
      else if (pagecount == 1) {
        that.setData({ loadmore: 'none', nodata: 'none', nomore: 'none' });
      }
      else if (data.page < pagecount) {
        that.setData({ loadmore: 'block', nodata: 'none', nomore: 'none' });
      } else if (data.page == pagecount) {
        that.setData({ loadmore: 'none', nodata: 'none', nomore: 'block' });
      }
    });
  },
  openImage:function(event){
    wx.previewImage({
      current: event.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: this.data.productinfo.Imgs // 需要预览的图片http链接列表
    })
  },
  Find_ProductInfo: function (id) {
    var that = this;
    var data = {};
    data.act = "Find_ProductInfo";
    data.id = id;
    app.Ajax(data, function (json) {
      wx.hideLoading();
      var pricelist=new Array();
      for(var i=0;i<json.data.PriceList.length;i++){
        pricelist.push(json.data.PriceList[i].APrice);
      }
      var price="";
      var pricetext = json.data.Unit;
      if(json.data.PriceType==1){
        price=json.data.APrice.toFixed(2);
      }else{
        price = pricelist.Min().toFixed(2) + '-' + pricelist.Max().toFixed(2);
      }
      that.setData({
        productinfo: json.data,
        price: price,
        flag:json.data.IsStore?"cancel":"store",
        librarycount: json.data.LibraryCount,
        pricetext:pricetext
      });
      WxParse.wxParse('article', 'html', json.data.Context, that, 5);
      wx.stopPullDownRefresh();
    });
  },
  buy:function(e){
    if (util.GoLogin()) { return; }
    var act = e.currentTarget.dataset.act;
    this.setData({ zindex: 1, opacity: 0.5, bottom: 0, act:act});
  },
  close:function(){
    this.setData({ zindex: -1, opacity: 0, bottom: -940});
  },
  sure: function () {
    if (util.GoLogin()) { return; }
    if (this.data.productinfo.PriceType==2 && this.data.priceid==0){
      app.showError('请选择'+this.data.productinfo.PriceName.replace("选择",""));
      return;
    }
    var formats = this.data.formats.join(",");
    for(var i=0;i<this.data.productinfo.FormatList.length;i++){
      if (formats.indexOf("format"+(i+1)+"-")==-1){
        app.showError('请选择' + this.data.productinfo.FormatList[i].List[0].replace("选择", ""));
        return;
      }
    }
    if (this.data.count==0){
      app.showError('请输入购买数量');
      return;
    }
    if(this.data.act=="addcar"){
      this.Save_Car();
    }else{
      var postprice = this.data.productinfo.ExpressMoney;
      var img = this.data.productinfo.Img;
      var name = this.data.productinfo.Name;
      var productid = this.data.productinfo.ID;
      var format = new Array();
      format.push(this.data.pricetext);
      for (var i = 0; i < this.data.formats.length; i++) {
        format.push(this.data.formats[i].split('-')[1]);
      }
      var oprice = this.data.productinfo.OPrice.toFixed(2);
      var aprice = this.data.productinfo.APrice.toFixed(2);
      var unit = this.data.productinfo.Unit;
      if(this.data.productinfo.PriceType==2)
      {
        oprice=this.data.oprice;
        aprice = this.data.aprice.toFixed(2);
        unit = this.data.unit;
      }
      wx.navigateTo({
        url: '/pages/pay/pay?productid=' + productid + '&postprice=' + postprice + '&oprice=' + oprice + '&aprice=' + aprice + '&unit=' + unit + '&count=' + this.data.count + "&img=" + img + "&name=" + name + "&format=" + format.join("@") + "&from=productinfo",
      })
    }
    this.close();
  },
  store: function(e){
    if (util.GoLogin()) { return; }
    var that=this;
    var flag = e.currentTarget.dataset.flag;
    var data = {};
    data.act = "Save_Store";
    data.productid = this.data.productinfo.ID;
    data.flag = flag;
    app.Ajax(data, function (json) {
      app.showSuccess(json.msg);
    });

    if (flag == "store") {
      flag = "cancel";
    } else {
      flag = "store";
      setTimeout(function () {
        that.setData({ hidestore: "hidestore1" });
      }, 800)
    }
    this.setData({ hidestore: "hidestore2", flag: flag });
  },
  openShare:function(){
    wx.showShareMenu({})
  },
  checkformat:function(e){
    var formats=new Array();
    var format = e.currentTarget.dataset.format;
    var value = e.currentTarget.dataset.value;
    formats=this.data.formats;
    for (var i = formats.length-1;i>=0;i--){
      if(formats[i].indexOf(format+"-")>-1){
        formats.Remove(formats[i]);
      }
    }
    formats.push(format+"-"+value);
    formats.sort();
    this.setData({formats:formats});
  },
  checkprice:function(e){
    var priceid = e.currentTarget.dataset.priceid;
    var oprice = e.currentTarget.dataset.oprice;
    var aprice = e.currentTarget.dataset.aprice;
    var unit = e.currentTarget.dataset.pricetext;
    var librarycount = e.currentTarget.dataset.librarycount;
    var pricetext = e.currentTarget.dataset.pricetext;
    this.setData({ priceid: priceid, pricetext: pricetext, librarycount: librarycount, oprice:oprice,aprice:aprice, unit:unit, price: aprice.toFixed(2)});
  },
  AddCount:function(e){
    this.setData({ count: this.data.count + 1});
  },
  MinusCount: function (e) {
    if (this.data.count>1){
      this.setData({ count: this.data.count-1 });
    }
  },
  SetCount: function (e) {
    if (isNaN(e.detail.value) || e.detail.value.trim()=="") {
      this.setData({ count: this.data.count});
      app.showError("请输入购买数量");
      return;
    }
    this.setData({ count: parseInt(e.detail.value)});
  },
  Save_Car: function(){
    var format=new Array();
    if(this.data.productinfo.PriceType==2){
      format.push(this.data.pricetext);
    }
    for(var i=0;i<this.data.formats.length;i++){
      format.push(this.data.formats[i].split('-')[1]);
    }
    var oprice = this.data.productinfo.OPrice.toFixed(2);
    var aprice = this.data.productinfo.APrice.toFixed(2);
    var unit = this.data.productinfo.Unit;
    if (this.data.productinfo.PriceType == 2) {
      oprice = this.data.oprice;
      aprice = this.data.aprice;
      unit = this.data.unit;
    }
    var data = {};
    data.productid = this.data.productinfo.ID;
    data.aprice = aprice;
    data.oprice = oprice;
    data.unit = unit;
    data.count = this.data.count;
    data.ischeck = 1;
    data.format=format.join("&");
    data.flag="add";
    data.act = "Save_Car";
    wx.showLoading({
      title: '正在加入购物车...',
    })
    app.Ajax(data, function (json) {
      wx.hideLoading();
      app.showSuccess("成功加入购物车");
    });
  },
  changetab:function(e){
    var select = e.currentTarget.dataset.select;
    if (select =="reply"){
      this.Find_Reply();
    }
    this.setData({ select: select });
  },
  ScrollTop:function(){
    this.setData({ select: "reply" });
    this.Find_Reply();
    var query = wx.createSelectorQuery();
    query.selectAll('#reply,#baozhang,#swiper,#info').boundingClientRect()
    query.exec(function (res) {
      
      wx.pageScrollTo({
        scrollTop: res[0][0].height + res[0][1].height + res[0][2].height + res[0][3].height + 20
      })
    })
  }
})